package com.xiaoxiong.text;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

/**
 * 
 * @ClassName: StringHttp
 * @Description: http请求的类，用post方式的，调用post()
 * @author xiaoxiong
 * @date 2016年3月31日 下午6:14:05
 * 
 */
public class StringHttp {
	/**
	 * 上下文
	 */
	private Context mContext;
	/**
	 * 请求队列
	 */
	private RequestQueue mQueue;
	/**
	 * 消息
	 */
	private Handler mHandler;
	/**
	 * Post的参数
	 */
	private Map<String, String> postDatas;
	/**
	 * 保存数据用到
	 */
	private SharedPreferences nb_school_message;
	/**
	 * 是否需要保存cookies的标记
	 */
	private boolean isSaveCookies;
	/**
	 * 保存cookies用到的名字(key值)
	 */
	private String cookiesName;

	public StringHttp(Context mContext) {
		super();
		this.mContext = mContext;
		this.mQueue = Volley.newRequestQueue(this.mContext);
		this.isSaveCookies = false;
	}

	/**
	 * 
	 * @Title: DoPost
	 * @Description: 调用这个方法请求
	 * @param @param url 地址
	 * @param @param handler 消息
	 * @param @param postData post的数据
	 * @return void
	 * @throws
	 */
	public void Post(String url, Handler handler, Map<String, String> postData) {
		this.DoPost(url, handler, postData);
	}

	/**
	 * 
	 * @Title: Post
	 * @Description: 不用传参数时调用这个方法请求
	 * @param @param url
	 * @param @param handler
	 * @param @param isPopup
	 * @param @param isCanStop
	 * @param @param message
	 * @return void
	 * @throws
	 */
	public void Post(String url, Handler handler) {
		this.DoPost(url, handler, new HashMap<String, String>());
	}

	/**
	 * 
	 * @Title: Post
	 * @Description: 调用这个方法请求并获取cookies
	 * @param @param url
	 * @param @param handler
	 * @param @param postData
	 * @param @param isPopup
	 * @param @param sharedPreferences 存cookies的SharedPreferences
	 * @param @param cookiesName SharedPreferences中以cookiesName获取cookies
	 * @return void
	 * @throws
	 */
	public void Post(String url, Handler handler, Map<String, String> postData,
			SharedPreferences sharedPreferences, String cookiesName) {
		this.nb_school_message = sharedPreferences;
		this.isSaveCookies = true;
		this.cookiesName = cookiesName;
		this.DoPost(url, handler, postData);
	}

	/**
	 * 
	 * @Title: DoPost
	 * @Description: 调用这个方法请求
	 * @param @param url 地址
	 * @param @param handler 消息
	 * @param @param postData post的数据
	 * @return void
	 * @throws
	 */
	private void DoPost(String url, Handler handler,
			Map<String, String> postData) {
		this.mHandler = handler;
		this.postDatas = postData;

		// 服务器响应成功的回调
		Listener<String> listener = new Listener<String>() {
			@Override
			public void onResponse(String response) {
				Message msg = new Message();
				Bundle bundle = new Bundle();
				bundle.putString("Value", response);
				bundle.putBoolean("isSuccess", true);
				msg.setData(bundle);

				mHandler.sendMessage(msg);
			}

		};
		// 服务器响应失败的回调
		ErrorListener errorListener = new ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Message msg = new Message();
				Bundle bundle = new Bundle();
				String strResponse = error.toString();
				bundle.putString("Value", strResponse + "失败的回调");
				bundle.putBoolean("isSuccess", false);
				msg.setData(bundle);

				mHandler.sendMessage(msg);
			}
		};

		final StringRequest jsonrequest = new StringRequest(Method.POST, url,
				listener, errorListener) {

			// 获取cookies用到，重写该方法
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try {
					//获取数据的headers
					Map<String, String> responseHeaders = response.headers;
					//将内容设置为GBK编码
					String dataString = new String(response.data, "GBK");
					//如果需要保存cookies
					if (isSaveCookies) {
						// 获取cookies
						String rawCookies = responseHeaders.get("Set-Cookie");
						//保存cookies
						Editor editor = nb_school_message.edit();
						editor.putString(cookiesName, rawCookies);
						editor.commit();
					}

					return Response.success(dataString,
							HttpHeaderParser.parseCacheHeaders(response));
				} catch (Exception e) {
					return Response.error(new ParseError(e));
				}
			}
			
			//Post方式，需要先处理提交的参数(下次写Volley框架使用时会讲到)
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {

				Map<String, String> map = new HashMap<String, String>();

				Set<String> set = postDatas.keySet();
				Iterator<String> iterator = set.iterator();

				while (iterator.hasNext()) {
					String key = iterator.next();
					map.put(key, postDatas.get(key));
				}
				return map;
			}
		};

		//设置超时时间、重连次数
		jsonrequest.setRetryPolicy(new DefaultRetryPolicy(5000,
				DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

		//将请求加入队列
		mQueue.add(jsonrequest);
		mQueue.start();
	}
}
